package com.allwees.bs.c.module.order.context.listener;

import com.allwees.bs.c.module.order.context.event.OrderRefundFailedEvent;
import com.allwees.bs.c.module.order.entity.OrderEntity;
import com.allwees.bs.c.module.order.entity.OrderItemEntity;
import com.allwees.bs.c.module.order.repository.OrderItemRepository;
import com.allwees.bs.c.module.order.repository.OrderRepository;
import com.allwees.bs.c.module.user.dao.DeviceDao;
import com.allwees.sender.AppSender;
import com.allwees.sender.MessageSender;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class OrderRefundFailedListener {

    private final static String LINK = "AccountOrderDetailPage";
    private final static String NOTIFY_TITLE = "Refund failed！";
    private final static String NOTIFY_CONTENT = "We apologize, your refund request has been rejected!";

    @Autowired
    private OrderRepository orderRepository;

    @Resource
    private DeviceDao deviceDao;

    @Autowired
    private OrderItemRepository orderItemRepository;

    @Autowired
    private MessageSender messageSender;

    @Async
    @EventListener
    @Transactional
    public void on(OrderRefundFailedEvent event) {

        String orderItemUuid = (String) event.getSource();

        OrderItemEntity orderItem = orderItemRepository.getByUuid(orderItemUuid);

        if (orderItem == null) {
            return;
        }

        OrderEntity order = orderRepository.getByUuid(orderItem.getOrderUuid());
        if (order == null) {
            return;
        }

        String jpushId = deviceDao.getPushId(order.getUserUuid());
        send(jpushId, order.getUserUuid(), order.getUuid(), order.getMainPhoto());
    }

    private void send(String jpushId, String userUuid, String orderUuid, String mainPhoto) {

        if (StringUtils.isNotBlank(jpushId)) {
            AppSender.push(jpushId, NOTIFY_TITLE, NOTIFY_CONTENT);
        }

        Map<String, String> params = new HashMap<>();
        params.put("orderUuid", orderUuid);
        messageSender.send(userUuid, NOTIFY_TITLE, NOTIFY_CONTENT, LINK, mainPhoto, params);
    }
}
